// 配置
const API_CONFIG = {
    baseURL: '/learning', // 后端API地址
    endpoints: {
        resources: '/resources/',
        search: '/resources/',
        download: '/resources/download/'
    },
    timeout: 10000 // 10秒超时
};

// 全局变量
let currentResources = [];
let currentFilter = 'all';
let currentPage = 1;
let isUsingMockData = false;
let searchTimeout = null;
// 修改全局变量部分
let totalPages = 1;
let pageSize = 12;
let pagination = null; // 新增：存储分页信息

// API请求函数
async function makeAPIRequest(endpoint, options = {}) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), API_CONFIG.timeout);

    try {
        const response = await fetch(`${API_CONFIG.baseURL}${endpoint}`, {
            ...options,
            signal: controller.signal,
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken'),
                ...options.headers
            }
        });

        clearTimeout(timeoutId);

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        return await response.json();
    } catch (error) {
        clearTimeout(timeoutId);
        throw error;
    }
}

// 修改API请求函数，添加分页参数
async function fetchResources(page = 1, category = '', type = '') {
    showLoading(true);
    updateDataSourceIndicator('正在连接后端...');
    console.log("category",  category)
    console.log("type",  type)
    try {
        // 构建API参数
        const params = new URLSearchParams({
            page: page.toString(),
            page_size: pageSize.toString()
        });

        if (category && category !== 'all') {
            params.append('category', category);
        }

        if (type && type !== 'all') {
            params.append('type', type);
        }

        const data = await makeAPIRequest(`${API_CONFIG.endpoints.resources}?${params}`);

        if (data.success) {
            currentResources = data.resources;
            pagination = data.pagination; // 存储分页信息
            currentPage = data.pagination.current_page;
            totalPages = data.pagination.total_pages;
            isUsingMockData = false;
            updateDataSourceIndicator('后端数据');
            hideError();

            // 渲染分页器
            renderPagination();
        } else {
            throw new Error(data.error || '请求失败');
        }
    } catch (error) {
        console.warn('后端请求失败，使用模拟数据：', error.message);

        // 模拟分页逻辑
        let filteredMockData = mockResources;
        if (category && category !== 'all') {
            filteredMockData = mockResources.filter(resource =>
                resource.category === category || resource.type === category
            );
        }

        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        currentResources = filteredMockData.slice(startIndex, endIndex);

        // 模拟分页信息
        pagination = {
            current_page: page,
            total_pages: Math.ceil(filteredMockData.length / pageSize),
            total_count: filteredMockData.length,
            has_next: endIndex < filteredMockData.length,
            has_previous: page > 1
        };

        currentPage = page;
        totalPages = pagination.total_pages;
        isUsingMockData = true;
        updateDataSourceIndicator('模拟数据');
        showError('无法连接到后端服务，当前显示模拟数据');

        renderPagination();
    } finally {
        showLoading(false);
        renderResources();
        updateCategoryCounts();
    }
}


// 修改搜索函数，支持分页
async function searchResources(page = 1) {
    const query = document.getElementById('searchInput').value.trim();
    const searchButton = document.getElementById('searchButton');

    // 防抖处理
    if (searchTimeout) {
        clearTimeout(searchTimeout);
    }

    searchTimeout = setTimeout(async () => {
        if (!query) {
            await fetchResources(page);
            return;
        }

        searchButton.disabled = true;
        searchButton.innerHTML = '<div class="spinner" style="width: 16px; height: 16px; margin-right: 5px;"></div>搜索中...';
        showLoading(true);

        try {
            if (!isUsingMockData) {
                // 后端搜索
                const params = new URLSearchParams({
                    q: query,
                    page: page.toString(),
                    page_size: pageSize.toString()
                });

                const data = await makeAPIRequest(`${API_CONFIG.endpoints.search}?${params}`);

                if (data.success) {
                    currentResources = data.resources;
                    pagination = data.pagination;
                    currentPage = data.pagination.current_page;
                    totalPages = data.pagination.total_pages;
                    updateDataSourceIndicator('后端搜索');
                    renderPagination();
                } else {
                    throw new Error(data.error || '搜索失败');
                }
            } else {
                // 本地搜索模拟数据
                const filtered = mockResources.filter(resource =>
                    resource.title.toLowerCase().includes(query.toLowerCase()) ||
                    resource.description.toLowerCase().includes(query.toLowerCase()) ||
                    resource.content.toLowerCase().includes(query.toLowerCase())
                );

                const startIndex = (page - 1) * pageSize;
                const endIndex = startIndex + pageSize;
                currentResources = filtered.slice(startIndex, endIndex);

                pagination = {
                    current_page: page,
                    total_pages: Math.ceil(filtered.length / pageSize),
                    total_count: filtered.length,
                    has_next: endIndex < filtered.length,
                    has_previous: page > 1
                };

                currentPage = page;
                totalPages = pagination.total_pages;
                updateDataSourceIndicator('本地搜索');
                renderPagination();
            }

            hideError();
        } catch (error) {
            console.warn('搜索请求失败：', error.message);
            showError('搜索服务暂时不可用');
        } finally {
            searchButton.disabled = false;
            searchButton.innerHTML = `
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                        <circle cx="11" cy="11" r="8" stroke="currentColor" stroke-width="2"/>
                        <path d="m21 21-4.35-4.35" stroke="currentColor" stroke-width="2"/>
                    </svg>
                    搜索
                `;
            showLoading(false);
            renderResources();
        }
    }, 500);
}

// 显示加载状态
function showLoading(show) {
    const indicator = document.getElementById('loadingIndicator');
    indicator.style.display = show ? 'flex' : 'none';
}

// 显示错误信息
function showError(message) {
    const container = document.getElementById('errorContainer');
    container.innerHTML = `<div class="error-message">${message}</div>`;
}

// 隐藏错误信息
function hideError() {
    const container = document.getElementById('errorContainer');
    container.innerHTML = '';
}

// 更新数据源指示器
function updateDataSourceIndicator(text) {
    const indicator = document.getElementById('dataSourceIndicator');
    indicator.textContent = text;
    indicator.className = `data-source-indicator ${isUsingMockData ? 'data-source-mock' : 'data-source-api'}`;
}

// 更新分类计数
function updateCategoryCounts() {
    const categories = ['anxiety', 'depression', 'stress', 'mindfulness', 'relationship', 'sleep'];
    categories.forEach(category => {
        const count = currentResources.filter(resource => resource.category === category).length;
        const element = document.getElementById(`${category}-count`);
        if (element) {
            element.textContent = `${count} 个资源`;
        }
    });
}

// 渲染资源列表
function renderResources() {
    const grid = document.getElementById('resourcesGrid');
    const filteredResources = filterResources();

    grid.innerHTML = '';
    if (filteredResources.length === 0) {
        grid.innerHTML = '<div style="grid-column: 1/-1; text-align: center; padding: 40px; color: #718096;">未找到相关资源</div>';
        return;
    }

    filteredResources.forEach(resource => {
        const card = createResourceCard(resource);
        grid.appendChild(card);
    });
}

// 新增：渲染分页器函数
function renderPagination() {
    const paginationContainer = document.getElementById('pagination');

    if (!pagination || pagination.total_pages <= 1) {
        paginationContainer.innerHTML = '';
        return;
    }

    let paginationHTML = '';

    // 上一页按钮
    if (pagination.has_previous) {
        paginationHTML += `<button onclick="changePage(${currentPage - 1})" title="上一页">‹</button>`;
    }

    // 页码按钮逻辑
    const totalPages = pagination.total_pages;
    const currentPageNum = pagination.current_page;

    let startPage, endPage;

    if (totalPages <= 7) {
        // 如果总页数小于等于7，显示所有页码
        startPage = 1;
        endPage = totalPages;
    } else {
        // 否则只显示部分页码
        if (currentPageNum <= 4) {
            startPage = 1;
            endPage = 7;
        } else if (currentPageNum >= totalPages - 3) {
            startPage = totalPages - 6;
            endPage = totalPages;
        } else {
            startPage = currentPageNum - 3;
            endPage = currentPageNum + 3;
        }
    }

    // 第一页
    if (startPage > 1) {
        paginationHTML += `<button onclick="changePage(1)" ${1 === currentPageNum ? 'class="active"' : ''}>1</button>`;
        if (startPage > 2) {
            paginationHTML += '<span style="padding: 8px;">...</span>';
        }
    }

    // 页码范围
    for (let i = startPage; i <= endPage; i++) {
        paginationHTML += `<button onclick="changePage(${i})" ${i === currentPageNum ? 'class="active"' : ''}>${i}</button>`;
    }

    // 最后一页
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            paginationHTML += '<span style="padding: 8px;">...</span>';
        }
        paginationHTML += `<button onclick="changePage(${totalPages})" ${totalPages === currentPageNum ? 'class="active"' : ''}>${totalPages}</button>`;
    }

    // 下一页按钮
    if (pagination.has_next) {
        paginationHTML += `<button onclick="changePage(${currentPage + 1})" title="下一页">›</button>`;
    }

    paginationContainer.innerHTML = paginationHTML;
}

// 创建资源卡片
function createResourceCard(resource) {
    const card = document.createElement('div');
    card.className = 'resource-card';
    card.onclick = () => openResourceModal(resource);

    const stars = '★'.repeat(Math.floor(resource.rating)) + '☆'.repeat(5 - Math.floor(resource.rating));

    card.innerHTML = `
                <div class="resource-type ${resource.type}">${getTypeLabel(resource.type)}</div>
                <h3 class="resource-title">${resource.title}</h3>
                <p class="resource-description">${resource.description}</p>
                <div class="resource-meta">
                    <div class="resource-duration">
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none">
                            <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                            <polyline points="12,6 12,12 16,14" stroke="currentColor" stroke-width="2"/>
                        </svg>
                        ${resource.duration}
                    </div>
                    <div class="resource-rating">
                        <span style="color: #fbbf24;">${stars}</span>
                        <span>${resource.rating}</span>
                    </div>
                </div>
            `;

    return card;
}

// 获取资源类型标签
function getTypeLabel(type) {
    const labels = {
        'girl': '👧🏻 心情小秘密',
        'boy': '👦🏻 成长大冒险',
        'trouble': '💭 成长小烦恼',
        'knowledge': '🌱 青春悄悄话'
    };
    return labels[type] || type;
}

// 筛选资源
function filterResources() {
    if (currentFilter === 'all') {
        return currentResources;
    }
    return currentResources.filter(resource =>
        resource.type === currentFilter || resource.category === currentFilter
    );
}

// 设置事件监听器
function setupEventListeners() {
    // 筛选标签点击事件
    document.querySelectorAll('.filter-tag').forEach(tag => {
        tag.addEventListener('click', function () {
            document.querySelectorAll('.filter-tag').forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            currentFilter = this.getAttribute('data-filter');

            // 重置到第一页
            currentPage = 1;
            const filterCategory = currentFilter === 'all' ? '' : currentFilter;
            let type_map = ['girl', 'boy']
            if (type_map.includes(filterCategory)) {
                fetchResources(1, '',filterCategory);
            }
            else{
                fetchResources(1, filterCategory);
            }
        });
    });

    // 搜索输入事件
    document.getElementById('searchInput').addEventListener('input', function () {
        if (this.value.trim() === '') {
            currentPage = 1;
            fetchResources();
        }
    });

    // 回车搜索
    document.getElementById('searchInput').addEventListener('keypress', function (e) {
        if (e.key === 'Enter') {
            currentPage = 1;
            searchResources();
        }
    });
}

// 分类函数
function filterByCategory(category) {
    document.querySelectorAll('.filter-tag').forEach(t => t.classList.remove('active'));
    const filterTag = document.querySelector(`[data-filter="${category}"]`);
    if (filterTag) {
        filterTag.classList.add('active');
    }

    currentFilter = category;
    // 重置到第一页并重新获取数据
    currentPage = 1;

    let filterType = '';
    let filterCategory = category === 'all' ? '' : category;
    let type_map = ['girl', 'boy']
    if (type_map.includes(category)) {
        filterCategory = ''
        filterType = category;
    }
    else {
        filterType = 'all';
    }

    fetchResources(1, filterCategory, filterType);
}

// 打开资源详情模态框
function openResourceModal(resource) {
    const modal = document.getElementById('resourceModal');
    const title = document.getElementById('modalTitle');
    const body = document.getElementById('modalBody');

    title.textContent = resource.title;

    // 显示内容预览
    const previewContent = resource.content.length > 500
        ? resource.content.substring(0, 500) + '...'
        : resource.content;

    // body.innerHTML = `
    //             <div class="resource-type ${resource.type}" style="margin-bottom: 15px;">
    //                 ${getTypeLabel(resource.type)}
    //             </div>
    //             <p style="margin-bottom: 20px; color: #718096;">${resource.description}</p>
    //             <div style="margin-bottom: 20px;">
    //                 <strong>时长:</strong> ${resource.duration} |
    //                 <strong>评分:</strong> ${resource.rating}/5.0
    //             </div>
    //
    //             <h4 style="margin-bottom: 10px;">内容预览:</h4>
    //             <div class="preview-content">${previewContent}</div>
    //
    //             <div style="margin-top: 20px; padding: 20px; background: #f7fafc; border-radius: 8px;">
    //                 <h4 style="margin-bottom: 10px;">学习建议:</h4>
    //                 <ul style="margin-left: 20px;">
    //                     <li>建议在安静的环境中学习</li>
    //                     <li>可以做笔记记录重要要点</li>
    //                     <li>学习后尝试在生活中实践</li>
    //                     <li>如有疑问可以咨询专业人员</li>
    //                 </ul>
    //             </div>
    //
    //             <div class="modal-actions">
    //                 <button class="action-button view-button" onclick="viewFullContent(${resource.id})">
    //                     <svg width="16" height="16" viewBox="0 0 24 24" fill="none" style="margin-right: 5px;">
    //                         <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" stroke="currentColor" stroke-width="2"/>
    //                         <circle cx="12" cy="12" r="3" stroke="currentColor" stroke-width="2"/>
    //                     </svg>
    //                     查看完整内容
    //                 </button>
    //             </div>
    //         `;

    body.innerHTML = `
                <div class="resource-type ${resource.type}" style="margin-bottom: 15px;">
                    ${getTypeLabel(resource.type)}
                </div>
                <p style="margin-bottom: 20px; color: #718096;">${resource.description}</p>
                
                <h4 style="margin-bottom: 10px;">完整内容:</h4>
                <div class="preview-content" style="max-height: 400px;">${resource.content}</div>
               
    `;



    modal.style.display = 'block';
}

// 查看完整内容
function viewFullContent(resourceId) {
    const resource = currentResources.find(r => r.id === resourceId);
    if (!resource) return;

    const body = document.getElementById('modalBody');
    body.innerHTML = `
                <div class="resource-type ${resource.type}" style="margin-bottom: 15px;">
                    ${getTypeLabel(resource.type)}
                </div>
                <p style="margin-bottom: 20px; color: #718096;">${resource.description}</p>
                
                <h4 style="margin-bottom: 10px;">完整内容:</h4>
                <div class="preview-content" style="max-height: 400px;">${resource.content}</div>
                
                <div class="modal-actions">
                    <button class="action-button view-button" onclick="openResourceModal(${JSON.stringify(resource).replace(/"/g, '&quot;')})">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" style="margin-right: 5px;">
                            <polyline points="15,18 9,12 15,6" stroke="currentColor" stroke-width="2"/>
                        </svg>
                        返回预览
                    </button>
                    <button class="action-button download-button" onclick="downloadResource(${resource.id})">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" style="margin-right: 5px;">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" stroke="currentColor" stroke-width="2"/>
                            <polyline points="7,10 12,15 17,10" stroke="currentColor" stroke-width="2"/>
                            <line x1="12" y1="15" x2="12" y2="3" stroke="currentColor" stroke-width="2"/>
                        </svg>
                        下载资源
                    </button>
                </div>
            `;
}

// 下载资源
async function downloadResource(resourceId) {
    const resource = currentResources.find(r => r.id === resourceId);
    if (!resource) return;

    try {
        if (!isUsingMockData) {
            // 尝试从后端下载
            const response = await fetch(`${API_CONFIG.baseURL}${API_CONFIG.endpoints.download}/${resourceId}`);
            if (response.ok) {
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `${resource.title}.${resource.type === 'article' ? 'pdf' : 'pdf'}`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
                return;
            }
        }

        // 模拟下载
        const content = `${resource.title}\n\n${resource.description}\n\n${resource.content}`;
        const blob = new Blob([content], {type: 'text/plain;charset=utf-8'});
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${resource.title}.txt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);

    } catch (error) {
        console.error('下载失败：', error);
        alert('下载失败，请稍后重试');
    }
}

// 关闭模态框
function closeModal() {
    document.getElementById('resourceModal').style.display = 'none';
}

// 修改页面切换函数
function changePage(page) {
    if (page < 1 || page > totalPages || page === currentPage) {
        return;
    }

    const query = document.getElementById('searchInput').value.trim();

    if (query) {
        // 搜索状态下的分页
        searchResources(page);
    } else {
        // 正常浏览状态下的分页
        const category = currentFilter === 'all' ? '' : currentFilter;
        let type_map = ['girl', 'boy']
        if (type_map.includes(category)) {
            fetchResources(page, '',category);
        }
        else{
            fetchResources(page, category);
        }

    }

    // 滚动到顶部
    document.querySelector('.resources-content').scrollTop = 0;
}

// 点击模态框外部关闭
window.onclick = function (event) {
    const modal = document.getElementById('resourceModal');
    if (event.target === modal) {
        modal.style.display = 'none';
    }
}

// 初始化页面
function initPage() {
    setupEventListeners();
    fetchResources();
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initPage);

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 添加获取分页信息的辅助函数
function getPaginationInfo() {
    return pagination || {
        current_page: 1,
        total_pages: 1,
        total_count: 0,
        has_next: false,
        has_previous: false
    };
}
